// pages/shop/shop.js
const PAGES = require('../../utils/pages.js')
var base = require('../../base.js');  //路径可能做相应调整
const _ = base._; //翻译函数
const { HTTP } = require('../../lib/http.js')
const { URL } = require('../../lib/urls.js')
const { getUserToken, getUserInfo } = require('../../lib/user.js')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    _t: [],
    showModal: false,
    dataList: [],
    selectData:null,
    // 获取列表相关参数
    isFromSearch: true, // 用于判断searchSongList数组是不是空数组，默认true，空的数组
    searchPageNum: 1,   // 设置加载的第几次，默认是第一次
    callbackcount: 6,   //返回数据的个数
    searchLoading: false, //"上拉加载"的变量，默认false，隐藏
    searchLoadingComplete: false,  //“没有数据”的变量，默认false，隐藏
    isShowNullView: false,

    kwValue:"",//搜索关键字
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      _t: base._t(), //翻译
    });
    if (!getIsLogin()) {
      wx.navigateTo({
        url: PAGES.index,
      })
      return;
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    this.fetchProductList();
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.getCartCount();
    if (typeof this.getTabBar === 'function' &&
      this.getTabBar()) {
      this.getTabBar().setData({
        selected: 3
      })
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.setData({
      searchPageNum: 1,  //每次触发上拉事件，把searchPageNum+1
      isFromSearch: true  //触发到上拉事件，把isFromSearch设为为false
    });
    this.fetchProductList();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    let that = this;
    if (this.data.searchLoading && !this.data.searchLoadingComplete) {
      this.setData({
        searchPageNum: that.data.searchPageNum + 1,  //每次触发上拉事件，把searchPageNum+1
        isFromSearch: false  //触发到上拉事件，把isFromSearch设为为false
      });
      this.fetchProductList();
    }
  },

  showDialogBtn: function (e) {
    let Index = e.currentTarget.dataset.index;//点击的商品下标值
    let nowSelect = this.data.dataList[Index];
    var that = this
    that.setData({
      selectData: nowSelect,
      showModal: true,
    })
  },
  /**
   * 弹出框蒙层截断touchmove事件
   */
  preventTouchMove: function () {
  },
  /**
   * 隐藏模态对话框
   */
  hideModal: function () {
    var that = this
    that.setData({
      showModal: false
    });
  },
  // 提交订单
  submitTap: function () {
    wx.navigateTo({
      url: PAGES.orderQrLh,
    })
  },
  // 查看我的商品券
  gotoMyQuanTap: function () {
    wx.navigateTo({
      url: PAGES.myVouchers,
    })
  },
  onChange(e) {
    this.setData({
      kwValue: e.detail
    });
  },
  onSearch() {
    this.fetchProductList();
  },

  fetchProductList: function () {
    let that = this;
    let searchPageNum = that.data.searchPageNum,//把第几次加载次数作为参数
      callbackcount = that.data.callbackcount; //返回数据的个数
    HTTP({
      url: URL.goods.mergeProductList,
      userToken: getUserToken(),
      data: {
        KeyWord: that.data.kwValue,
        PageIndex: searchPageNum,
        PageSize: callbackcount,
        MemberId: getUserInfo().memberId,
      },
      success: (ress) => {
        wx.stopPullDownRefresh();
        var res = ress.Data;
        var ylist = res.ProductList||[];
        if (ylist.length > 0) {
          console.log("hlw:" + res)
          let searchList = [];
          var list = [];
          for (var i = 0; i < res.ProductList.length; i++) {
            var model = res.ProductList[i];
            model.type=0;
            model.amount=1;
            if (model.CProductList.length>0) {
              model.type=1;
              let productInfos = [];
              for (var cpindex in model.CProductList) {
                var cppro = model.CProductList[cpindex];
                cppro.payType = 0;
                productInfos.push(cppro);
              }
              model.ProductInfos = productInfos;
            }
            list.push(model);
          }
          //如果isFromSearch是true从data中取出数据，否则先从原来的数据继续添加
          this.data.isFromSearch ? searchList = list : searchList = that.data.dataList.concat(list)
          this.setData({
            dataList: searchList, //获取数据数组
            searchLoading: true,   //把"上拉加载"的变量设为false，显示
            isShowNullView: searchList.length > 0 ? false : true
          });
          if (res.data.records.length < callbackcount) {
            //数据已加载完毕
            that.setData({
              searchLoadingComplete: true, //把“没有数据”设为true，显示
              searchLoading: false  //把"上拉加载"的变量设为false，隐藏
            });
          }
          //没有数据了，把“没有数据”显示，把“上拉加载”隐藏
        } else {
          if (that.data.searchPageNum == 1) {
            that.setData({
              dataList: [],
              isShowNullView: true
            })
          }
          that.setData({
            searchLoadingComplete: true, //把“没有数据”设为true，显示
            searchLoading: false  //把"上拉加载"的变量设为false，隐藏
          });
        }
      }
    })
  },
  // 提交订单
  submitTcTap: function () {
    let data = JSON.stringify(this.data.selectData);
    wx.navigateTo({
      url: PAGES.orderQrLh + '?data=' + encodeURIComponent(data)
    })
  },
  //获取购物车商品数量
  getCartCount: function () {
    let that = this;
    HTTP({
      url: URL.goods.cartCount,
      userToken: getUserToken(),
      data: {
      },
      success: (ress) => {
        var res = ress.Data;
        console.log("hlw:" + res)
        var list = [];
        for (var i in that.getTabBar().data.list) {
          var model = that.getTabBar().data.list[i];
          if (i == 2) {
            model.tagNum = res;
          }
          list.push(model);
        }
        that.getTabBar().setData({
          list: list
        })
      },
      fail: (res) => {
        console.log(res)
        wx.showToast({
          title: res.msg,
          icon: 'none'
        })
      }
    })
  },
})